<template>
  <div class="container tree-list-layout">
    <!--左侧树-->
    <treeCert ref="treeCert" class="box-left" @click="handleTreeClick" style="width: 400px !important" @afterLoad="afterLoadTree" :queryType="queryType"/>

    <!--右侧区域-->
    <div style="padding-top: 10px">
      <customForm :labelWidth="80" >
        <template #content>
          <customFormItem
            label="当前节点"
            name="msg"
            :parent="_self"
            :form="form"
            :type="constCommon.formItemType.slot.name"
          >
            <template #content>
              <div v-html="cpPropSubtitle"></div>
            </template>
          </customFormItem>
          <customFormItem label="级联展示" name="cascade" :parent="_self" :form="form"  :type="constCommon.formItemType.switch.name" @change="loadDtl"
                          help="选中后，将显示当前节点的所有子级数据"
                          style="margin-left: -90px;"
          />
          <span style="margin-left: -90px;">
            <small class="span-tip" v-if="queryType == 'warn'">
                仅显示已审核，未作废的已过期资质或者效期在30天以内的
              </small>
              <small class="span-tip" v-if="queryType == 'view'">
                仅显示已审核，并且未作废的资质
              </small>
          </span>

        </template>
      </customForm>
    </div>
    <data-view
      propViewKey="cert_warn"
      propViewForm="cert/sp_cert_detail.vue"
      :propIsTdesign="true"
      :propAutoFetchData="false"
      ref="dvList"
      class="box-right"
      style="width: calc(100% - 400px) !important"
      :propUserParam="{queryType: queryType}"
      @extra-button-click="extraButtonClick"
      :propInitData="selectedNode"
      :propOnlyQueryAll="queryType == 'view'"
      :propTableOpWidth="queryType == 'view' ? 80 : 200"
      @after-load="handleReady"
      :propSubtitle="cpPropSubtitle"
      :propFilterBtnByData="propFilterBtnByData"
      @afterTableDataChange="menuActiveCall"
    />

    <customDrawer  title="资质历史查看" ref="customDrawerHistory" hideConfirm >
      <template #content>
        <data-view ref="dvHistory" propViewKey="cert_history" :propAutoFetchData="false" />
      </template>
    </customDrawer>
  </div>
</template>

<script>
import treeCert from '@/components/custom/bus/treeCert.vue'
import customAnchor from '@/components/custom/form/customAnchor.vue'
import customUpload from '@/components/custom/form/customUpload.vue'

export default {
  help: '供应商资质维护-增删改查列表',
  props: {
    /**
     * @Description：查询类型 view: 查看 warn: 预警
     */
    queryType: {
      type: String,
      default: () => 'crud'
    }
  },
  watch: {
    '$route.query.id': {
      immediate: true,
      handler(newVal) {
        if (!newVal) {
          return
        }
        this.idQuery = newVal
        this.$nextTick(() => {
          let wrapper = this.$newWrapper()
          wrapper.eq('id', id)
          this.$refs.dvList.setQueryWrapperOnce(wrapper)
        })
      }
    },
  },
  data() {
    return {
      selectedNode: {},
      form: {
        cascade: false
      },
      idQuery: ''
    }
  },
  components: {
    customUpload,
    treeCert, customAnchor
  },
  methods: {
    handleReady() {
      if (this.strings.isNotBlank(this.idQuery)) {
        this.$refs.dvList.viewRow(this.idQuery)
        this.idQuery = ''
      }
    },
    // 加载数据
    loadDtl() {
      let wrapper = this.$newWrapper()
      console.log('this.selectedNode', this.selectedNode)
      if (this.selectedNode.id) {
        wrapper.eq('supplier_id', this.selectedNode.spId)
        //非级联，只差当前节点
        if (!this.form.cascade) {
          wrapper.eq('target_describe_id', this.selectedNode.targetDescribeId)
        }

        let typeName = this.selectedNode.typeName
        if (typeName == this.constCommon.certTypeNameMap.mfg.key) { //厂商节点
          wrapper.ne('business_type_code', this.constCommon.certTypeNameMap.sp.businessTypeCode)
          wrapper.eq('manufacturer_id', this.selectedNode.mfgId)
        } else if (typeName == this.constCommon.certTypeNameMap.cat.key) { // 品类节点
          wrapper.notIn('business_type_code', [this.constCommon.certTypeNameMap.sp.businessTypeCode,this.constCommon.certTypeNameMap.mfg.businessTypeCode])
          wrapper.eq('manufacturer_id', this.selectedNode.mfgId)
          wrapper.eq('catalog_id', this.selectedNode.catId)
        }else if (typeName == this.constCommon.certTypeNameMap.matr.key) { // 商品节点
          wrapper.eq('business_type_code', this.constCommon.certTypeNameMap.matr.businessTypeCode)
          wrapper.eq('manufacturer_id', this.selectedNode.mfgId)
          wrapper.eq('catalog_id', this.selectedNode.catId)
          wrapper.eq('material_id', this.selectedNode.matrId)
        }
      } else {
        wrapper.eq('1', '-1')
      }
      this.$refs.dvList.setQueryWrapper(wrapper)
    },
    // 加载历史资质
    lodHistory(row) {
      let wrapper = this.$newWrapper()
        .eq('certificate_repository_id', this.strings.defaultIfBlank(row.id, '-1'))
      this.$refs.dvHistory.setQueryWrapper(wrapper)
    },

    // 树点击
    handleTreeClick(data) {
      this.selectedNode = data
      console.log('this.selectedNode', this.selectedNode)
      this.loadDtl()
    },

    // 扩展按钮
    extraButtonClick(para) {
      let buttonKey = para.button.key
      // 作废
      if (buttonKey == 'close') {
        this.close(para.data)
        return
      }

      // 升级
      if (buttonKey == 'upgrade') {
        this.$refs.dvList.viewRow(para.data.id, false)
        return
      }

      // 历史
      if (buttonKey == 'history') {
        this.lodHistory(para.data)
        this.$refs.customDrawerHistory.show()
        return
      }

      // 上传资质
      if (buttonKey == 'addCert') {
        if (!this.selectedNode.id) {
          this.utilMessage.warning('请选择左侧需要添加的节点')
          return
        }
        switch (this.selectedNode.typeName) {
          //品类节点
          case 'cat': {
            if (this.selectedNode.catId == '0') {
              this.utilMessage.warning('未分类品类不需要维护资质')
              return
            }
          }
        }

        this.$refs.dvList.ocAddnew()
        return
      }
    },

    // 作废
    close(data) {
      this.utilMessage.confirm('是否作废该资质?', () => {
        this.utilVue.loadShow(true)
        this.$ajax.post(`/cert/certificate_repositorys/close/` + data.id).then((resp) => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            this.utilMessage.success('作废成功')
            this.loadDtl()
            this.menuActiveCall()
          }
        })
      })
    },

    // 树加载后
    afterLoadTree(node) {
      this.handleTreeClick(node)
    },

    // 按钮过滤
    propFilterBtnByData(button, data) {
      let btnCodeList = []
      btnCodeList.push(this.constCommon.btnKeyMap.formTop.delete)
      let isTmpData = data.id && data.id.indexOf('temp_') != -1
      if (
        isTmpData
        && (btnCodeList.includes(button.key) || btnCodeList.includes(button.code))
      ) {
        return false
      }

      let btnCodeList2 = []
      btnCodeList2.push(this.constCommon.btnKeyMap.formTop.save)
      if (
        data.id && data.id.indexOf('temp_') == -1
        && (btnCodeList2.includes(button.key) || btnCodeList2.includes(button.code))
      ) {
        return false
      }

      return true
    },
    menuActiveCall() {
      this.$refs.treeCert.load()
    }
  },
  created() {
    this.$parent.menuActiveCall = this.menuActiveCall
  },

  computed: {
    cpNodeInfo() {
      if (!this.selectedNode.id) {
        return {
          type: '未选择',
          title: '',
        }
      }
      let typeName = this.selectedNode.typeName
      let info  = {}
      info.type = this.constCommon.certTypeNameMap[typeName].title
      info.title = this.selectedNode.title
      return info
    },

    // 弹框子标题
    cpPropSubtitle() {
      if (!this.selectedNode.id) {
        return ''
      }
      return global.utils.getDictLabel(
        this.constCommon.certTypeNameMap[this.selectedNode.typeName].businessTypeCode,
        global.constCommon.dictType.certBusinessType,
        '',
        true)
    }
  }
}
</script>
